<template>
  <view class="content">
    <tui-form ref="formRef" :show-message="false" :model="formData">
      <!-- 单位工程 -->
      <tui-form-item arrow labelWidth='180' asterisk label="单位工程" prop="unitProject" @click="popupShow=true">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.unitProject"
          placeholder="请选择"></tui-input>
      </tui-form-item>
      <tui-bottom-popup :zIndex="1002" :height="600" :maskZIndex="1001" :show="popupShow" @close="popupShow=false">
        <tui-cascade-selection height="200px" :defaultItemList='defaultItemList' :itemList="itemList"
          @complete="complete"></tui-cascade-selection>
      </tui-bottom-popup>

      <!-- 分部工程 -->
      <tui-form-item arrow labelWidth='180' asterisk label="分部工程" prop="subsection" @click="popupShow2=true">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.subsection"
          placeholder="请选择"></tui-input>
      </tui-form-item>
      <tui-bottom-popup :zIndex="1002" :height="600" :maskZIndex="1001" :show="popupShow2" @close="popupShow2=false">
        <tui-cascade-selection height="200px" :defaultItemList='defaultItemLists' :itemList="itemList2"
          @complete="complete2"></tui-cascade-selection>
      </tui-bottom-popup>
      <tui-form-item labelWidth='180' asterisk label="验收编号" prop="branchCode">
        <tui-input padding="0" :borderBottom="false" v-model="formData.branchCode" placeholder="请输入"></tui-input>
      </tui-form-item>
      <tui-form-item labelWidth='180' asterisk label="分项工程数" prop="branchQuantity">
        <tui-input padding="0" type='number' :borderBottom="false" v-model="formData.branchQuantity"
          placeholder="请输入"></tui-input>
      </tui-form-item>
      <tui-form-item labelWidth='180' asterisk label="检验批数量" prop="lotQuantity">
        <tui-input padding="0" type='number' :borderBottom="false" v-model="formData.lotQuantity"
          placeholder="请输入"></tui-input>
      </tui-form-item>
      <!-- 验收日期 -->
      <tui-form-item arrow labelWidth='180' asterisk label="验收日期" prop="checkDate" @click="openCalendar">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.checkDate"
          placeholder="请选择"></tui-input>
      </tui-form-item>
      <tui-calendar ref="calendar" :initStartDate="initStartDate" :initEndDate="initEndDate" lunar isFixed :type="2"
        @change="changeCalendar"></tui-calendar>
      <tui-form-item labelWidth='180' asterisk label="备注" prop="memo">
        <tui-input padding="0" :borderBottom="false" v-model="formData.memo" placeholder="请输入"></tui-input>
      </tui-form-item>
      <tui-section title="未分项验收检验批信息" is-line background="#f8f8f8"></tui-section>
      <tui-no-data v-if="checkboxItems.length===0" :fixed="false" imgUrl="/static/img_nodata.png">暂无数据</tui-no-data>
      <tui-checkbox-group @change="checkBoxChange">
        <tui-label v-for="(item,index) in checkboxItems" :key="index">
          <tui-list-cell>
            <view class="thorui-align__center">
              <tui-checkbox :checked="item.checked" :value="item.value" color="#f8683c" borderColor="#999"
                style="margin-right: 20px;"></tui-checkbox>
              <view style="display: flex;flex-direction: column;">
                <view>{{item.lotName}}</view>
                <view>【检验批容量】{{item.lotQuantity}}</view>
                <view>【检验批部位】{{item.lotPart}}</view>
              </view>
            </view>
          </tui-list-cell>
        </tui-label>
      </tui-checkbox-group>
      <view style="padding:0 10px 10px 10px;">
        <tui-form-button text="提交" @click="submit"></tui-form-button>
      </view>
    </tui-form>
  </view>
</template>

<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app'
  import { ref, onMounted } from 'vue';
  import {
    getProjectLotNoCheckedList,
    getFullProjectBranchInfoById,
    reStartProjectBranchProcess,
    updateProjectBranch,
    startProjectBranchProcess,
    addProjectBranch,
    getProjectUnitProjectManageList,
    getSysSubsectionManageList
  } from '@/apis/branch.js';
  const popupShow = ref(false)
  const popupShow2 = ref(false)
  const itemList = ref([])
  const itemList2 = ref([])
  const formRef = ref(null);
  const calendar = ref(null);
  const defaultItemList = ref([])
  const defaultItemLists = ref([])

  const rules = [
    {
      name: "unitProject",
      rule: ["required"],
      msg: ["请选择单位工程"]
    }, {
      name: "subsection",
      rule: ["required"],
      msg: ["请选择分部工程"]
    }, {
      name: "branchCode",
      rule: ["required"],
      msg: ["请输入验收编号"]
    }, {
      name: "branchQuantity",
      rule: ["required", 'isNum'],
      msg: ["请输入分项工程数", '请输入数字']
    }, {
      name: "lotQuantity",
      rule: ["required", 'isNum'],
      msg: ["请输入检验批数量", '请输入数字']
    }, {
      name: "checkDate",
      rule: ["required"],
      msg: ["请选择验收日期"]
    }, {
      name: "memo",
      rule: ["required"],
      msg: ["请输入备注"]
    }];

  const formData = ref({
    unitProject: '',
    subsection: '',
    branchCode: "",
    branchName: "",
    branchQuantity: '',
    checkEndDate: "",
    checkStartDate: "",
    lotQuantity: '',
    memo: "",
    projectLotViewRespList: [],
    subAndUnitProjectIds: [],
    sysSubsectionIds: [],
    checkDate: ''
  })

  const projectId = uni.getStorageSync('projectInfo').id
  const isEdit = ref(false)
  const branchid = ref(0)
  const checkboxItems = ref([])
  const initEndDate = ref('')
  const initStartDate = ref('')

  onMounted(() => {
    getList()
  });

  onLoad(({ branchId }) => {
    //   //如果有lotId就是编辑状态 再次提交时发起重新送审
    //   //添加一个状态判断编辑还是新增
    isEdit.value = false
    if (branchId) {
      branchid.value = branchId
      isEdit.value = true
      getFullProjectBranchInfoById(branchId).then(res => {
        console.log(res.data.data);
        let data = res.data.data
        formData.value = data
        formData.value.unitProject = data.unitProjectName + '-' + data.subUnitProjectName
        formData.value.subAndUnitProjectIds = [data.unitProjectId, data.subUnitProjectId]
        formData.value.subsection = data.subsectionName + '-' + data.tenderSubsectionName + '-' + data.branchName
        formData.value.sysSubsectionIds = [data.subsectionId, data.tenderSubsectionId, data.branchId]
        setTimeout(() => {
          defaultItemList.value = [data.unitProjectName, data.subUnitProjectName]
          defaultItemLists.value = [data.subsectionName, data.tenderSubsectionName, data.branchName]
        }, 100)


        initStartDate.value = data.checkStartDate
        initEndDate.value = data.checkEndDate
        formData.value.checkDate = data.checkStartDate + ' 至 ' + data.checkEndDate

        getProjectLotNoCheckedList(projectId, data.branchId).then(res => {
          let arr = data.projectLotViewRespList.map(e => e.projectLotId)
          checkboxItems.value = res.data.data.map(e => ({ ...e, checked: arr.includes(e.projectLotId) ? true : false, value: '' + e.projectLotId }))
          formData.value.projectLotViewRespList = data.projectLotViewRespList
        })
      })
    }
  })

  const checkBoxChange = (e) => {
    formData.value.projectLotViewRespList = checkboxItems.value.filter((item) => e.detail.value.includes(item.value));
  }

  //单位工程
  const complete = (e) => {
    formData.value.unitProject = e.result.map(e => e.text).join('-')
    formData.value.subAndUnitProjectIds = e.result.map(e => e.value)
    popupShow.value = false
  }


  //分部工程
  const complete2 = (e) => {
    console.log(e);
    formData.value.subsection = e.result.map(e => e.text).join('-')
    formData.value.sysSubsectionIds = e.result.map(e => e.value)
    getProjectLotNoCheckedList(projectId, e.result[2].value).then(res => {
      console.log(res.data.data);
      checkboxItems.value = res.data.data.map(e => ({ ...e, checked: false, value: '' + e.projectLotId }))
      formData.value.branchName = e.result[2].text
    })
    popupShow2.value = false
  }

  //验收日期
  const openCalendar = () => {
    calendar.value.show()
  }

  const changeCalendar = (e) => {
    formData.value.checkDate = e.startDate + ' 至 ' + e.endDate
    formData.value.checkStartDate = e.startDate
    formData.value.checkEndDate = e.endDate
  }

  //获取列表数据
  const getList = () => {
    getProjectUnitProjectManageList(projectId).then(res => {
      itemList.value = handleData(res.data.data);
    })
    getSysSubsectionManageList().then(res => {
      itemList2.value = handleData(res.data.data);
    })
  }

  //转换格式
  const handleData = (data) => {
    return data.map(item => ({
      text: item.nodeName,
      value: item.id,
      children: item.children ? handleData(item.children) : null
    }));
  }


  //提交表单
  const submit = async (values) => {
    if (isEdit.value === false) {
      //新增
      if (formRef.value) {
        formRef.value.validate(formData.value, rules, true).then((res) => {
          if (res.isPass && formData.value.projectLotViewRespList.length>0) {
            addProjectBranch(projectId, formData.value).then(res => {
              startProjectBranchProcess(res.data.data).then(res => {
                if (res.data.code === 200) {
                  uni.navigateTo({
                    url: '/pages/branch/branch'
                  })
                }
              })
            })
          }else{
            plus.nativeUI.toast('请选择未分项验收检验批信息')
          }
        })
      }
    } else {


      //编辑
      if (formRef.value) {
        formRef.value.validate(formData.value, rules, true).then((res) => {
          if (res.isPass && formData.value.projectLotViewRespList.length>0) {
            updateProjectBranch(formData.value).then(res => {
              reStartProjectBranchProcess(branchid.value).then(res => {
                if (res.data.code === 200) {
                  uni.navigateTo({
                    url: '/pages/branch/branch'
                  })
                }
              })
            })
          }else{
            plus.nativeUI.toast('请选择未分项验收检验批信息')
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .content {
    background-color: #fff;

    // padding: 0px 10px 10px 10px;
    .thorui-align__center {
      display: flex;
      align-items: center;
    }

    .tui-text {
      font-size: 30rpx;
      padding-left: 12rpx;
    }

    .container {
      height: 100vh;
      background-color: #eeeeee;

      .formClass {
        padding: 0 20rpx;
        display: flex;
        flex-direction: column;
      }
    }
  }
</style>